import {getKeyData} from './utils.js'

const handleStateMentType = (originVal,resultVal,type,valType)=>{
	if(valType === 'date'){
		originVal = new Date(originVal).getTime()
		if(resultVal === 'now'){
			resultVal = new Date().getTime()
		}else{
			resultVal = new Date(resultVal).getTime()
		}
	}
	if(type === '='){
		return originVal === resultVal
	}else if(type === '!='){
		return originVal !== resultVal
	}else if(type === '>'){
		return originVal > resultVal
	}else if(type === '<'){
		return originVal < resultVal
	}else if(type === '<='){
		return originVal <= resultVal
	}else if(type === '>='){
		return originVal >= resultVal
	}
}

// 条件判断的规则
// 每个条件之间是 && 的关系
// 每个条件内的每个字段之间是 && 的关系
export default (stateMents,data,dataType,props={},variable={})=>{
	var trueNum = 0	//条件语句为true的数量
	// 每一个条件语句都成立,才能保持result为true
	stateMents.forEach(state=>{
		var nowDateType = dataType
		if(dataType === 'event'){
			if(state.source === 'transKey'){
				nowDateType = 'list'
			}else{
				nowDateType = state.source
			}
		}
		var fieldTrueNum = 0	//字段比较的总结果
		// 每一个字段都需要满足条件语句,才能保持fieldResult为true
		state.fields.forEach((field,index)=>{
			var realField = field,targetVal = '';
			//如果是多样式列表的条件判断，则字段需去除前缀
			if(nowDateType === 'list'){
				var idx = field.indexOf('Array%krt_')
				realField = field.substr(idx+10)
			}
			if(nowDateType === 'list' || !nowDateType){
				targetVal = getKeyData(realField,data,1) + ''
			}else if(nowDateType === 'props'){
				targetVal = props[field] + ''
			}else if(nowDateType === 'variable'){
				variable.some(vari => {
					if (vari.keyName === field) {
						targetVal = vari.val + ''
						return true
					}
				})
			}else if(nowDateType === 'storage'){
				var storageVal = '';
				// #ifdef H5
				storageVal = localStorage.getItem(field);
				// #endif
				// #ifdef MP
				storageVal = uni.getStorageSync(field);
				// #endif
				targetVal = storageVal + ''
			}
			var fieldResult = false
			// 模式2:每个字段分别与对应顺序的值匹配
			// 模式1:每个字段与可能值匹配到一个即可
			if(state.mode === '2'){
				fieldResult = handleStateMentType(targetVal,state.val[index],state.type,state.valType)
			}else if(state.mode === '1'){
				fieldResult = state.val.some(val=>handleStateMentType(targetVal,val,state.type,state.valType))
			}
			if(fieldResult){
				fieldTrueNum++
			}
		})
		if(fieldTrueNum === state.fields.length){
			trueNum++
		}
	})
	return trueNum === stateMents.length
}